package moco.blatt4.datepickertest;

import java.util.GregorianCalendar;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TextView;

public class MyDatePicker extends Activity {

	private long start, end;
	private GregorianCalendar c = new GregorianCalendar();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_picker);
        
        
        DatePicker dpStart = (DatePicker) this.findViewById(R.id.datePickerStart);
        DatePicker dpEnd = (DatePicker) this.findViewById(R.id.datePickerEnd);
        
        dpStart.init(dpStart.getYear(), dpStart.getMonth(), dpStart.getDayOfMonth(), new OnDateChangedListener() {
			public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				setStart(year, monthOfYear, dayOfMonth);
				calcDiff();
			}


		});
        
        dpEnd.init(dpEnd.getYear(), dpEnd.getMonth(), dpEnd.getDayOfMonth(), new OnDateChangedListener() {
			public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				setEnd(year, monthOfYear, dayOfMonth);
				calcDiff();
			}
		});
        
        setStart(dpStart.getYear(), dpStart.getMonth(), dpStart.getDayOfMonth());
        setEnd(dpEnd.getYear(), dpEnd.getMonth(), dpEnd.getDayOfMonth());
    }
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_date_picker, menu);
        return true;
    }
    
    private void calcDiff() {
		c.setTimeInMillis(start-end);
		// diff + 1 Tag da Ende nicht inklusive --> 0:0:0
		((TextView) findViewById(R.id.diff)).setText( "Differenz in Tagen: " + (Math.abs((start-end)/(1000*60*60*24))+1) );
		
	}
    
	public void setStart(int year, int monthOfYear, int dayOfMonth) {
		this.c.set(year, monthOfYear, dayOfMonth, 0, 0, 0);
		this.start = c.getTimeInMillis();
	}

	public void setEnd(int year, int monthOfYear, int dayOfMonth) {
		c.set(year, monthOfYear, dayOfMonth, 0, 0, 0);
		this.end = c.getTimeInMillis();
	}
}
